package org.example.controller;

import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.example.Mapper.UserMapper;
import org.example.domain.ActivityRecord;
import org.example.domain.User;
import org.example.service.impl.ActivityRecordServiceImpl;
import org.example.untils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@RestController
@RequestMapping("activityRecord")
public class ActivityRecordController {

    @Autowired
    private ActivityRecordServiceImpl activityRecordServiceImpl;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/getActivityRecordsByUserId")
    public Result getActivityRecordsByUserId(@Param("userId") Integer userId){
        ActivityRecord[] activityRecords=activityRecordServiceImpl.getActivityRecordsByUserId(userId);
        return new Result(200,"获取成功",activityRecords);
    }

    @GetMapping("/getActivityRecordsByActivityId")//根据活动id获取活动记录
    public Result getActivityRecordsByActivityId(@Param("activityId") Integer activityId){
        ActivityRecord[] activityRecords= activityRecordServiceImpl.getActivityRecordsByActivityId(activityId);
        Result result=new Result();
        result.setCode(200);
        result.setData(activityRecords);
        return result;
    }

    @GetMapping("/updateActivityRecordIsDoByActivityRecordId")//更改指定id的活动记录的签到状态
    public Result updateActivityRecordIsDoByActivityRecordId
            (@RequestParam("activityRecordId") Integer activityRecordId){
        Result result=new Result();
        Integer status=activityRecordServiceImpl.updateActivityRecordIsDoByActivityRecordId(activityRecordId);
        if(status==0){//修改成功
            result.setCode(200);
            result.setMessage("修改成功~");
        } else if(status==1){
            result.setCode(201);
            result.setMessage("该条记录正在申请中，请先前往审核页面，拒绝该条记录的申请，才能将其修改为缺席！");
        } else if(status==2){
            result.setCode(201);
            result.setMessage("该条记录已被标识为通过素拓申请，无法进行修改！");
        }
        return result;
    }

    @PostMapping("/addActivityRecord")
    public Result addActivityRecord(@RequestBody ActivityRecord activityRecord){
        Integer result=activityRecordServiceImpl.addActivityRecord(activityRecord);//结果为0表示其已经报名过该项活动，
        // 为1表示报名成功
        if(result==0){
            return new Result(201,"请勿重复报名",null);
        } else if(result==1){
            return new Result(201,"已无报名余额",null);
        } else if(result==2){
            return new Result(200,"报名成功",null);
        } else if(result==3){
            User user=userMapper.getAllById(activityRecord.getUserId());
            return new Result(202,"处于处罚时间",user.getPunishDate());
        } else {
            return new Result(201,"活动已签到",null);
        }
    }

    @GetMapping("/getUsersByActivityId")
    public Result getUsersByActivityId(@Param("activityId") Integer activityId){
        ArrayList<User> users=activityRecordServiceImpl.getUsersByActivityId(activityId);
        return new Result(200,"获取成功",users);
    }

    @GetMapping("/deleteActivityRecordById")
    public Result deleteActivityRecordById(@Param("id") Integer id,
                                           @Param("activityId") Integer activityId){//用户取消活动报名
        activityRecordServiceImpl.deleteActivityRecordById(id,activityId);//将这条活动记录删除，同时释放报名余额
        return  new Result(200,"取消成功",null);
    }

    @GetMapping("/deleteActivityRecordByUserIdAndActivityId")
    public Result deleteActivityRecordByUserIdAndActivityId(@Param("userId") Integer userId,
                                                            @Param("activityId") Integer activityId){
        Integer result=activityRecordServiceImpl.deleteActivityRecordByUserIdAndActivityId(userId,activityId);
        if (result==0){
            return new Result(201,"未查询到此条报名记录",null);
        } else if(result==1){
            return new Result(200,"取消成功",null);
        } else {
            return new Result(201,"活动已签到，无法取消",null);
        }
    }

    @GetMapping("/getActivityRecordExcel")//导出活动报名记录
    public ResponseEntity<byte[]> getActivityRecordExcel(@Param("activityId") Integer activityId) throws IOException {
        // 创建一个新的Excel工作簿
        Workbook workbook = new HSSFWorkbook();
        // 创建一个工作表
        Sheet sheet = workbook.createSheet("Sheet1");
        // 创建行和单元格，并填充数据
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("序列");
        cell = row.createCell(1);
        cell.setCellValue("姓名");
        cell = row.createCell(2);
        cell.setCellValue("学号");
        cell = row.createCell(3);
        cell.setCellValue("班级");
        ArrayList<User> users=activityRecordServiceImpl.getUsersByActivityId(activityId);
        for(int i=0;i<users.size();i++){
            row = sheet.createRow(i+1);
            cell = row.createCell(0);
            cell.setCellValue(i+1);
            cell = row.createCell(1);
            cell.setCellValue(users.get(i).getName());
            cell = row.createCell(2);
            cell.setCellValue(users.get(i).getAccount());
            cell = row.createCell(3);
            cell.setCellValue(users.get(i).getClassName());
        }
        // 将Excel文件写入字节数组输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        // 设置响应头，告诉浏览器返回的是一个Excel文件
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "活动记录表.xlsx");
        // 返回Excel文件的字节数组
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(outputStream.toByteArray());
    }
}
